package com.yfbao.horizon.demo;

import com.yfbao.horizon.model.MyMessageListener;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisClusterConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisSentinelConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import redis.clients.jedis.JedisPoolConfig;

public class ManualRedisMessageListenerContainerExample {

    public static void main(String[] args) {
        // 创建 Redis 连接工厂
        RedisConnectionFactory connectionFactory = createRedisConnectionFactory();

        // 创建 Redis 消息监听器容器
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        // 添加消息监听器和监听的频道或模式
        container.addMessageListener(new MyMessageListener(), new PatternTopic("yourChannel"));
        System.out.println("begin start");
        // 启动容器
        container.start();

        // 阻塞当前线程，保持容器运行
        System.out.println("after start");
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static RedisConnectionFactory createRedisConnectionFactory() {
        // 创建 Jedis 连接工厂
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
//        spring.redis.host= 127.0.0.1
////        spring.redis.port= 6379
////        spring.redis.password=Seeyon@123
////        spring.redis.database=0
        // 配置 Redis 主机和端口
        connectionFactory.setHostName("127.0.0.1");
        connectionFactory.setPort(6379);
        connectionFactory.setPassword("Seeyon@123");
        connectionFactory.setDatabase(0);

        // 可选：设置密码
        // connectionFactory.setPassword("yourPassword");

        // 配置连接池
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10);
        poolConfig.setMaxIdle(5);
        poolConfig.setMinIdle(1);
        connectionFactory.setPoolConfig(poolConfig);

        // 初始化连接工厂
        connectionFactory.afterPropertiesSet();
        return connectionFactory;
    }
}
